import { ref, onMounted, onBeforeUnmount } from 'vue';

const playDom = ref(null);
const isPlay = ref(false);
const startTime = ref(null);
const endTime = ref(null);

export const resetTime = () => {
  if (playDom.value) {
    playDom.value.pause();
  }

  playDom.value = null;
};

export function useMedia(ref) {
  //
  const play = () => {
    if (playDom.value) {
      playDom.value.pause();
    }
    setTimeout(() => {
      setMediaDom(ref.value);
    });
  };

  const pause = () => {
    setMediaDom(null);
  };

  onMounted(() => {
    resetTime();
    ref.value.addEventListener('play', play, false);
    ref.value.addEventListener('pause', pause, false);
  });

  onBeforeUnmount(() => {
    ref.value.removeEventListener('play', play);
    ref.value.removeEventListener('pause', pause);
    resetTime();
    pause();
  });

  function setMediaDom(dom) {
    playDom.value = dom;
  }

  return { setMediaDom, playDom };
}

export function useMediaTime() {
  return { isPlay, startTime, endTime, resetTime };
}
